package com.song.study.springclouddemo.redis;


import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/redis")
public class RedisController {

    @Autowired
    private RedisTemplate redisTemplate;
    String baseKey = "base_key_";
    //@PostConstruct
    public void init(){

        ValueOperations valueOperations = redisTemplate.opsForValue();

        for (int i = 0; i < 1000; i++) {
            valueOperations.set(baseKey + i, " this result num:"+i + " ");
            System.out.println("wire success....");
        }
    }


    @GetMapping(path = "/pip/line")
    public Object pipline(){
        List<String> list = redisTemplate.executePipelined(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                List<String> list = new ArrayList<>();
                for (int i = 10; i < 50; i++) {
                    redisConnection.openPipeline();
                    redisConnection.get((baseKey + i).getBytes());
                }
                return null;
            }
        });
        System.out.println(JSON.toJSONString(list));

        ValueOperations valueOperations = redisTemplate.opsForValue();
        for (int i = 10; i < 50; i++) {
            Object o = valueOperations.get((baseKey + i).getBytes());
            System.out.println(o);
        }
        return list;
    }
}
